<template>
  <div class="simple-color-test">
    <h2>🎨 简单颜色测试</h2>
    
    <div class="controls">
      <el-button @click="connect" :disabled="isConnected" type="primary">
        连接服务器
      </el-button>
      <el-button @click="disconnect" :disabled="!isConnected" type="danger">
        断开连接
      </el-button>
      <el-button @click="createRoom" :disabled="!isConnected" type="success">
        创建房间
      </el-button>
      <el-button @click="joinRoom" :disabled="!isConnected" type="warning">
        加入房间
      </el-button>
      <el-button @click="leaveRoom" :disabled="!isConnected" type="info">
        离开房间
      </el-button>
    </div>
    
    <div class="status">
      <p>连接状态: {{ isConnected ? '✅ 已连接' : '❌ 未连接' }}</p>
      <p>房间ID: {{ roomId || '无' }}</p>
      <p>当前玩家: {{ currentPlayer?.nickname || '无' }}</p>
      <p>头像颜色: <span class="color-display" :style="{ backgroundColor: currentPlayer?.avatarColor }">{{ currentPlayer?.avatarColor || '无' }}</span></p>
      <p>画笔颜色: <span class="color-display" :style="{ backgroundColor: currentPlayer?.brushColor }">{{ currentPlayer?.brushColor || '无' }}</span></p>
    </div>
    
    <div class="players">
      <h3>玩家列表</h3>
      <div v-for="player in players" :key="player.id" class="player">
        <span class="player-name">{{ player.nickname }}</span>
        <span class="player-avatar" :style="{ backgroundColor: player.avatarColor }">{{ player.avatarColor }}</span>
        <span class="player-brush" :style="{ backgroundColor: player.brushColor }">{{ player.brushColor }}</span>
        <span class="player-owner" v-if="player.isOwner">👑</span>
      </div>
    </div>
    
         <div class="log">
       <h3>日志</h3>
       <div class="log-controls">
         <el-button @click="clearLogs" size="small" type="info">清空日志</el-button>
         <el-button @click="exportLogs" size="small" type="success">导出日志</el-button>
         <el-button @click="checkColors" size="small" type="warning">检查颜色</el-button>
         <el-button @click="generateReport" size="small" type="primary">生成报告</el-button>
       </div>
       <div v-for="log in logs.slice(-10)" :key="log.id" class="log-item">
         {{ log }}
       </div>
     </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { createSignalRService } from '@/services/socketService'
import { useGameStore } from '@/stores/game'
import { colorDebugger } from '@/utils/colorDebugger'

const gameStore = useGameStore()
const isConnected = ref(false)
const roomId = ref('')
const currentPlayer = ref(null)
const players = ref([])
const logs = ref([])

const signalRService = createSignalRService(gameStore)

function addLog(message) {
  const timestamp = new Date().toLocaleTimeString()
  logs.value.push(`[${timestamp}] ${message}`)
  if (logs.value.length > 50) logs.value.shift()
}

async function connect() {
  try {
    addLog('正在连接...')
    await signalRService.connect()
    isConnected.value = true
    addLog('✅ 连接成功')
  } catch (error) {
    addLog(`❌ 连接失败: ${error.message}`)
  }
}

async function disconnect() {
  try {
    await signalRService.disconnect()
    isConnected.value = false
    addLog('🔌 已断开连接')
  } catch (error) {
    addLog(`❌ 断开失败: ${error.message}`)
  }
}

async function createRoom() {
  try {
    const roomCode = 'test-' + Math.random().toString(36).substr(2, 6)
    const playerId = 'player-' + Math.random().toString(36).substr(2, 9)
    
    currentPlayer.value = {
      id: playerId,
      nickname: '测试房主',
      color: '',
      isOwner: true
    }
    
    addLog(`🏠 创建房间: ${roomCode}`)
    await signalRService.createRoom(roomCode, '测试房间', 6, '', playerId, '测试房主')
    roomId.value = roomCode
    addLog(`✅ 房间创建成功: ${roomCode}`)
  } catch (error) {
    addLog(`❌ 创建房间失败: ${error.message}`)
  }
}

async function joinRoom() {
  try {
    const playerId = 'player-' + Math.random().toString(36).substr(2, 9)
    
    currentPlayer.value = {
      id: playerId,
      nickname: '测试玩家',
      color: '',
      isOwner: false
    }
    
    const targetRoom = roomId.value || 'test-room'
    addLog(`👤 加入房间: ${targetRoom}`)
    await signalRService.joinRoom(targetRoom, playerId, '测试玩家')
    addLog(`✅ 成功加入房间: ${targetRoom}`)
  } catch (error) {
    addLog(`❌ 加入房间失败: ${error.message}`)
  }
}

async function leaveRoom() {
  try {
    if (currentPlayer.value && roomId.value) {
      addLog('👋 离开房间...')
      await signalRService.leaveRoom(roomId.value, currentPlayer.value.id)
      addLog('✅ 已离开房间')
      currentPlayer.value = null
      roomId.value = ''
    }
  } catch (error) {
    addLog(`❌ 离开房间失败: ${error.message}`)
  }
}

onMounted(() => {
  // 监听游戏状态变化
  const unsubscribe = gameStore.$subscribe((mutation, state) => {
    if (mutation.type === 'patch') {
      players.value = state.players
      if (state.currentPlayer) {
        currentPlayer.value = state.currentPlayer
        if (state.currentPlayer.avatarColor) {
          addLog(`🎨 玩家头像颜色已分配: ${state.currentPlayer.avatarColor}`)
        }
        if (state.currentPlayer.brushColor) {
          addLog(`🖌️ 玩家画笔颜色已分配: ${state.currentPlayer.brushColor}`)
        }
        
        // 调试颜色分配
        colorDebugger.debugColorAssignment(state.currentPlayer, 'GameStore')
      }
      
      // 调试游戏存储状态
      colorDebugger.debugGameStore(gameStore)
    }
  })
  
  // 监听SignalR事件
  signalRService.on('Connected', () => {
    addLog('🔗 SignalR连接成功')
  })
  
  signalRService.on('PlayerJoined', (data) => {
    addLog(`👤 玩家加入: ${data.Nickname} (头像: ${data.AvatarColor}, 画笔: ${data.BrushColor})`)
    colorDebugger.debugColorAssignment(data, 'PlayerJoined')
  })
  
  signalRService.on('PlayerLeft', (data) => {
    addLog(`👋 玩家离开: ${data.PlayerId}`)
  })
  
  signalRService.on('RoomCreated', (data) => {
    addLog(`🏠 房间创建成功: ${data.RoomCode}`)
    colorDebugger.debugSignalREvent('RoomCreated', data)
  })
  
  signalRService.on('RoomInfo', (data) => {
    addLog(`📋 房间信息: ${data.Players?.length || 0} 个玩家`)
    colorDebugger.debugSignalREvent('RoomInfo', data)
  })
  
  addLog('🚀 页面已加载')
  
  // 清理函数
  onUnmounted(() => {
    unsubscribe()
    signalRService.off('Connected')
    signalRService.off('PlayerJoined')
    signalRService.off('PlayerLeft')
    signalRService.off('RoomCreated')
    signalRService.off('RoomInfo')
  })
})

// 添加调试功能
function clearLogs() {
  colorDebugger.clearLogs()
  logs.value = []
  addLog('🧹 日志已清空')
}

function exportLogs() {
  colorDebugger.exportLogs()
  addLog('📤 日志已导出')
}

function checkColors() {
  const issues = colorDebugger.checkColorConsistency(players.value)
  if (issues.length === 0) {
    addLog('✅ 颜色一致性检查通过')
  } else {
    addLog(`⚠️ 发现 ${issues.length} 个颜色问题`)
    issues.forEach(issue => addLog(`  - ${issue}`))
  }
}

function generateReport() {
  const report = colorDebugger.generateReport()
  addLog('📊 调试报告已生成', report)
}
</script>

<style scoped>
.simple-color-test {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.controls {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.status {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.status p {
  margin: 5px 0;
}

.color-display {
  display: inline-block;
  width: 60px;
  height: 20px;
  border-radius: 4px;
  color: white;
  text-align: center;
  font-size: 12px;
  line-height: 20px;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

.players {
  margin-bottom: 20px;
}

.player {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px;
  border: 1px solid #ddd;
  margin-bottom: 5px;
  border-radius: 4px;
}

.player-name {
  font-weight: bold;
  min-width: 100px;
}

.player-avatar {
  width: 60px;
  height: 20px;
  border-radius: 4px;
  color: white;
  text-align: center;
  font-size: 12px;
  line-height: 20px;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

.player-brush {
  width: 60px;
  height: 20px;
  border-radius: 4px;
  color: white;
  text-align: center;
  font-size: 12px;
  line-height: 20px;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

.player-owner {
  font-size: 16px;
}

.log {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  max-height: 300px;
  overflow-y: auto;
}

.log-controls {
  display: flex;
  gap: 8px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.log-item {
  font-family: monospace;
  font-size: 12px;
  margin-bottom: 5px;
  padding: 2px 0;
}
</style>
